package com.gitee.farmer.im.service;

import com.alibaba.fastjson.JSONObject;
import com.gitee.farmer.im.entity.User;
import com.gitee.farmer.im.rabbit.sender.Sender;
import com.gitee.farmer.im.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * @author tech-farmer
 * @ClassName: UserService
 * @Description: (这里用一句话描述这个类的作用)
 * @date 2022/2/25 14:44
 */
@Service
@Slf4j
public class UserService {

    private final UserRepository repository;

    private final Sender sender;

    public UserService(UserRepository repository, Sender sender) {
        this.repository = repository;
        this.sender = sender;
    }

    @Transactional(rollbackFor = Exception.class)
    public int login(String userId){
        User user = repository.getUserByUserId(userId);
        final Date now = new Date();
        if(user == null){
            user = new User();
            user.setUserId(userId)
                    .setName(userId)
                    .setOnlineState(1)
                    .setLastOnlineTime(now);
            User save = repository.save(user);
        }else{
            user.setOnlineState(1)
                    .setLastOnlineTime(now);
            repository.save(user);
        }
        return 1;
    }

    public int logout(String userId) {
        User user = repository.getUserByUserId(userId);
        if(user != null){
            user.setOnlineState(0);
            repository.save(user);
            return 1;
        }
        return 0;
    }

    public int alive(String userId) {
        User user = repository.getUserByUserId(userId);
        if(user != null){
            user.setOnlineState(1)
                    .setLastOnlineTime(new Date());
            repository.save(user);
            return 1;
        }
        return 0;
    }

    @Scheduled(initialDelay = 30000,fixedRate = 60000)
    public void userHeartBreak(){
        final List<User> onlineUsers = repository.findByOnlineStateGreaterThan(0);
        for (User onlineUser : onlineUsers) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("to",onlineUser.getUserId());
            //掉线
            if(onlineUser.getOnlineState() == 2 && Date.from(LocalDateTime.now().minusMinutes(10).atZone(ZoneId.systemDefault()).toInstant()).after(onlineUser.getLastOnlineTime())){
                jsonObject.put("type","down");
                onlineUser.setOnlineState(0);
                repository.save(onlineUser);
            }else{
                onlineUser.setOnlineState(2);
                repository.save(onlineUser);
                jsonObject.put("type","heartbreak");
                jsonObject.put("text","ping");
            }
            sender.send(jsonObject.toJSONString());
        }
    }

    public Object findAll() {
        return repository.findAll();
    }
}
